package com.hmdp.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
@RequiredArgsConstructor
public class RedisIdWoker {

    private final long BeginTimeStamp = 1744560000L;
    private final int CountBase = 32;
    private final StringRedisTemplate stringRedisTemplate;

    public long nextID(String prefix) {

        // 1. 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSeconds = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSeconds - BeginTimeStamp;
        // 2. 生成序列号
        // 2.1 获取当前日期，要求精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + prefix + ":" + date);


        // 3. 拼接返回
        return timeStamp << CountBase | count;
    }

    // 获取当前时间戳
//    public static void main(String[] args) {
//        LocalDateTime localDateTime = LocalDateTime.of(2025, 4, 13, 16, 0);
//        long epochSecond = localDateTime.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(epochSecond);
//    }

}
